package com.lagou.assignment.servlet;

import com.lagou.assignment.model.Admin;
import com.lagou.assignment.service.AdminService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        System.out.println("获取到的用户名为:" + username);
        String password = request.getParameter("password");
        System.out.println("获取到的密码为:" + password);
        String remember = request.getParameter("remember");

        AdminService adminService = new AdminService();
        Admin admin = null;
        try {
            admin = adminService.adminLoginService(new Admin(username, password));
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (null == admin){
            System.out.println("登录失败,用户名或者密码错误");
            request.setAttribute("error", "登录失败,用户名密码错误!");
            //实现服务器跳转 共享request,response
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request, response);
        }else {
            System.out.println("登陆成功,欢迎使用");
            request.getSession().setAttribute("admin", admin);
            if ("1".equalsIgnoreCase(remember)){
                Cookie[] cookies = request.getCookies();
                for (Cookie tc : cookies) {
                    String value = tc.getValue();
                    String id = request.getSession().getId();
                    if (value.equals(id)){
                        System.out.println(value);
                        System.out.println(id);
                        tc.setMaxAge(86400);
                        tc.setPath("/");
                        response.addCookie(tc);
                    }
                }
                //将登陆成功后的用户信息存入session对象中实现多个请求共享
                request.getSession().setMaxInactiveInterval(3600*24);
            }
            //实现客户端跳转
            response.sendRedirect("info.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
